import { feedApi } from '/api/feed'
import { $utils, $event } from '/utils'
import { GlobalData } from '/store/state'
import { checkAuth } from '/store/actions'
import { getServer } from '/store/mutations'
Page({
  data: {
    theme: {} as DomoTheme,
    newFeed: [] as DomoFeed[],
    newFeedLastpage: false,
    hotFeedLastpage: false,
    hotPage: 1,
    hotFeed: [] as any[],
    id: 0,
    nav: ['最新', '热门'],
    currTab: 0,
    scrollTop: false,
    scrollClass: false,
    navigationHeight: GlobalData.navigationHeight,
    access: GlobalData.access,
    mineId: 0,
    admin: false,
  },
  async onLoad(query: any) {
    $event.on('after:theme', this, () => {
      this.setData({
        nav: ['最新', '热门'],
        newFeed: [] as DomoFeed[],
      })
      this.getInfo()
    })
    let id = query.id
    if (!id && query.scene) {
      const scene = $utils.parseQueryString(query.scene)
      id = scene.id
    }
    this.setData({ id })
    this.getData()
  },
  onShow() {
    this.setData!({
      navigationHeight: GlobalData.navigationHeight,
      access: GlobalData.access,
    })
    $event.on('after:boot', this, () => {
      this.setData({
        navigationHeight: GlobalData.navigationHeight,
        access: GlobalData.access,
      })
    })
    $event.on('editorTheme', this, (theme: DomoTheme) => {
      this.setData({
        theme,
      })
    })
  },
  onShareAppMessage() {
    this.setData({
      share: true,
    })
    return {
      path: $utils.getSharePath(),
    }
  },
  async getData() {
    const {
      data: { id },
    } = this
    const theme = await feedApi.getThemeDetail(id)
    this.setData({
      theme,
      id: theme.id,
    })
    this.getInfo()
    this.getUserId()
  },
  onPullDownRefresh() {
    this.setData({
      newFeedLastpage: false,
      hotFeedLastpage: false,
    })
    this.getData()
    wx.stopPullDownRefresh()
  },
  isAdmin() {
    const abilities: any = GlobalData.userAbilities
    this.setData({
      admin: abilities && abilities.some((v: any) => v.name === '[feed] Manage Theme'),
    })
  },
  getUserId() {
    const user = wx.getStorageSync(`${getServer()}/logged`).data
    this.setData({
      mineId: user.id,
    })
    this.isAdmin()
    return user.id
  },
  async getInfo() {
    const id = this.data.id
    const hotFeed = await feedApi.getThemeHotFeeds(id, this.data.hotPage)
    const newFeed = await feedApi.getThemeNewFeeds({ theme: id } as GetThemeNewFeedsPramas)
    this.setData({
      newFeed,
      hotFeed: hotFeed.data,
      newFeedLastpage: newFeed.length < 15,
      hotPage: hotFeed.meta.current_page,
      hotFeedLastpage:
        hotFeed.meta.current_page === hotFeed.meta.last_page ||
        hotFeed.meta.current_page > hotFeed.meta.last_page,
    })
  },
  async onReachBottom() {
    const cur = this.data.currTab
    const id = this.data.id
    if ((cur === 0 && this.data.newFeedLastpage) || (cur === 1 && this.data.hotFeedLastpage)) {
      wx.showToast({
        title: '已没有更多',
        icon: 'none',
      })
      return
    }
    wx.showLoading({
      title: '加载中',
    })
    if (cur === 0) {
      const after = $utils.getLastField(this.data.newFeed)
      const newFeed = await feedApi.getThemeNewFeeds({ theme: id, after } as GetThemeNewFeedsPramas)
      this.setData({
        newFeed: [...this.data.newFeed, ...newFeed],
        newFeedLastpage: newFeed.length < 15,
      })
    } else {
      const hotFeed = await feedApi.getThemeHotFeeds(id, this.data.hotPage + 1)
      this.setData({
        hotFeed: [...this.data.hotFeed, ...hotFeed.data],
        hotPage: hotFeed.meta.current_page,
        hotFeedLastpage:
          hotFeed.meta.current_page === hotFeed.meta.last_page ||
          hotFeed.meta.current_page > hotFeed.meta.last_page,
      })
    }
    wx.hideLoading()
  },
  switchTab(e: WechatMiniprogram.BaseEvent) {
    const index = e.currentTarget.dataset.index
    this.setData({
      currTab: index,
    })
  },
  onPageScroll() {
    this.fixedProductTitle()
    this.fixedTitle()
  },
  /** 判断是否滚动到了讨论 */
  fixedTitle() {
    if (!this.data.access.ugc) return
    const query = wx.createSelectorQuery().in(this)
    query.select('#talk').boundingClientRect()
    query.selectViewport().scrollOffset()
    query.exec((res: any) => {
      this.setData({
        scrollClass: res[0] ? res[0].top < 1 + this.data.navigationHeight : true,
      })
    })
  },
  /** 判断是否滚动到了标题 */
  fixedProductTitle() {
    const query = wx.createSelectorQuery().in(this)
    query.select('#title').boundingClientRect()
    query.selectViewport().scrollOffset()
    query.exec((res: any) => {
      this.setData({
        scrollTop: res[0] ? res[0].bottom < 1 + this.data.navigationHeight : true,
      })
    })
  },
  /** 讨论 */
  async talk() {
    await checkAuth()
    wx.showActionSheet({
      itemList: ['图片', '视频'],
      success(res) {
        switch (res.tapIndex) {
          case 0:
            wx.navigateTo({
              url: `/pages/publish/publish?type=image&about=theme`,
            })
            break

          case 1:
            wx.navigateTo({
              url: `/pages/publish/publish?type=video&about=theme`,
            })
            break
        }
      },
    })
  },
  /** 操作 */
  operation() {
    const itemList: any[] = []
    const isMine = this.data.theme.creator?.id === this.data.mineId
    if (isMine || this.data.admin) {
      itemList.push('编辑话题')
    } else {
      itemList.push('举报')
    }

    wx.showActionSheet({
      itemList: itemList,
      success: (res) => {
        switch (itemList[res.tapIndex]) {
          case '编辑话题':
            wx.navigateTo({
              url: `/pages/creat-theme/creat-theme?iseditor=true`,
            })
            break
          case '举报':
            wx.navigateTo({
              url: `/pages/report/report?type=theme&id=${this.data.theme.id}`,
            })
            break

          case '删除':
            feedApi
              .deleteTheme(this.data.theme.id)
              .then(() => {
                wx.showToast({
                  title: '删除成功',
                })
                $event.emit('after:deleteTheme', this.data.theme)
                setTimeout(() => {
                  wx.navigateBack({ delta: 1 })
                }, 1000)
              })
              .catch(() => {
                wx.showToast({
                  title: '删除失败',
                  icon: 'none',
                })
              })
            break
        }
      },
    })
  },
})
